<?php
namespace App\Task;

use App\Storage\ChatMessageMysql;
use App\Storage\OnlineUser;
use App\Storage\UserShopRelation;
use App\WebSocket\WebSocketAction;
use EasySwoole\EasySwoole\ServerManager;
use EasySwoole\EasySwoole\Swoole\Task\AbstractAsyncTask;

/**
 * 客服对接聊天
 * Class RoomTask
 * @package App\Task
 */
class RoomTask extends AbstractAsyncTask {

    protected function run($taskData, $taskId, $fromWorkerId, $flags = null)
    {
        // TODO: Implement run() method.
        $server = ServerManager::getInstance()->getSwooleServer();

        $userId = empty($taskData['userId']) ? 0 : intval($taskData['userId']) ;
        $isShop = empty($taskData['isShop']) ? 0 : intval($taskData['isShop']);

        $toUserId = empty($taskData['toUserId']) ? 0 : intval($taskData['toUserId']);
        if ($isShop == 0) {
            $userShopRelation = UserShopRelation::getInstance()->get($userId);
            $toUserId = $userShopRelation['shop_user_id'];
            $toUserFd = $userShopRelation['shop_user_fd'];
        }

        $payload = json_decode($taskData['payload'], true);

        if ($payload['action'] == 303) { // 有发送消息
            // 存聊天记录
            $userInfo = OnlineUser::getInstance()->get($taskData['fromFd']);
            $data['from_user_id'] = $userId;
            $data['action'] = WebSocketAction::ROOM_MESSAGE;
            $data['username'] = $userInfo['username'];
            $data['avatar'] = $userInfo['avatar'];
            $data['shop_id'] = $userInfo['shop_id'];
            $data['to_user_id'] = $toUserId;
            $data['is_shop'] = $isShop;
            $data['created'] = date("Y-m-d H:i:s");
            $data['content'] = $taskData['content'];
            $data['type'] = $taskData['type'];
            ChatMessageMysql::getInstance()->saveMessage($data);

            $data = json_encode($data,JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);


            // 推送当条信息
            $server->push($taskData['fromFd'], $data); // 给当前用户发信息

            if ($isShop == 0) {
                // todo: 暂时先给对应的客服发消息
                $connection = $server->connection_info($toUserFd);
                if ($connection['websocket_status'] == 3) {
                    $server->push($toUserFd, $data); // 给所指定客服发信息
                }
//                if ($shopId && $shopId > 0) {
//                    $keys = OnlineShop::getInstance($shopId)->allKeys();
//                    foreach ($keys as $shopUserId) {
//                        $pushInfo = OnlineShop::getInstance($shopId)->get($shopUserId);
//                        if ($pushInfo['shopId'] == $shopId) {
//                            $connection = $server->connection_info($pushInfo['fd']);
//                            if ($connection['websocket_status'] == 3) {
//                                $server->push($pushInfo['fd'], $data); // 给所有客服发信息
//                            }
//                        }
//                    }
//                }
            } elseif ($isShop == 1) {
                // TODO: 给对应的用户发消息
                foreach (OnlineUser::getInstance()->table() as $toFd => $userInfo) {
                    if ($userInfo['user_id'] == $toUserId) {
                        var_dump($toUserId.'_'.$toFd);
                        $connection = $server->connection_info($toFd);
                        if ($connection['websocket_status'] == 3) {
                            $server->push($toFd, $data);
                        }
                    }
                }
                // todo: copy上面代码，给所有客服也发信息，保持所有客服的消息同步。暂时先不同步
            }
        } else { // 非主动消息，例如 进入房间，离开房间等
            $connection = $server->connection_info($taskData['fromFd']);
            if ($connection['websocket_status'] == 3) {
                $server->push($taskData['fromFd'], $taskData['payload']);
            }
            // 以下是针对部分信息，给对应的客服推送
            // 进入房间
            if ($payload['action'] == WebSocketAction::USER_IN_ROOM || $payload['action'] == WebSocketAction::ROOM_SERVICE) {
                $connection = $server->connection_info($toUserFd);
                if ($connection['websocket_status'] == 3) {
                    $server->push($toUserFd, $taskData['payload']); // 给所指定客服发信息
                }
            }
            // 离开房间
            if ($payload['action'] == WebSocketAction::USER_OUT_ROOM) {
                $connection = $server->connection_info($toUserFd);
                if ($connection['websocket_status'] == 3) {
                    $server->push($toUserFd, $taskData['payload']); // 给所指定客服发信息
                    //移除用户客服关系绑定
                    UserShopRelation::getInstance()->delete($userId);
                }
            }

        }
        return true;
    }

    protected function finish($result, $task_id)
    {
        // TODO: Implement finish() method.
    }

}